import { Level, Points, Stick, BallType } from "./Config"; 
import Ball from "../../resources/prefabs/Ball";
import Line from "../../resources/prefabs/Line";
import MathUtil from "../framework/utils/MathUtil";
import EventManager from "../framework/core/EventManager";
import AudioPlayer from "../framework/core/AudioPlayer";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Game2 extends cc.Component {

    @property(cc.Prefab)
    ballPrefab: cc.Prefab = null;
    @property(cc.Prefab)
    linePrefab: cc.Prefab = null;
    @property(cc.Node)
    levelLayer:cc.Node = null; 
    @property(cc.Label)
    level:cc.Label = null

    @property({type:cc.AudioClip,tooltip:"钢琴音乐"})
    musicUrl:cc.AudioClip = null;
    @property({type:cc.AudioClip,tooltip:"钢琴音乐"})
    piano:cc.AudioClip = null; 
    @property({type:[cc.AudioClip],tooltip:"碰碎音乐"})
    shatter:cc.AudioClip[] = [];
    @property({type:[cc.AudioClip],tooltip:"吱吱声"})
    squeek:cc.AudioClip[] = [];
    @property({type:cc.AudioClip,tooltip:"吱吱声"})
    squeekUrl:cc.AudioClip = null;
    currLevelID:number =30;
    currLevelConfig:Level = null;
    balls:cc.Node[] = [];
    lines:cc.Node[] = [];
    limitClick:number = 0;
    isPassLock:boolean =false;
    isStar:boolean = false;

    linePool:cc.NodePool = null;
    ballPool:cc.NodePool = null;

    onLoad(){
        let physicsManager = cc.director.getPhysicsManager()
        var Bits = cc.PhysicsManager.DrawBits;
        physicsManager.enabled = true;
        //physicsManager.debugDrawFlags = Bits.e_jointBit | Bits.e_shapeBit; 
        cc.director.getPhysicsManager().gravity = cc.v2(0, -650);  
        this.linePool = new cc.NodePool("Line");
        this.ballPool = new cc.NodePool("Ball");
        EventManager.on("nextLevel",this.nextLevel,this);
        EventManager.on("checkPassLevel",this.checkPassLevel,this);
        EventManager.on("clickCheck",this.checkClick,this);
        EventManager.on("playShatter",this.playShatterEff,this);
        EventManager.on("playSqueek",this.playSqueekEff,this);
        EventManager.on("startDynamic",this.startDynamic,this);
        this.levelLayer.opacity = 0; 
        AudioPlayer.playMusic(this.musicUrl) 
    }   

    start () { 
        let level = localStorage.getItem("level") || 0; 
        this.currLevelID = Number(level); 
        this.loadLevel(this.currLevelID);
    }   
 
    loadLevel(level){ 
        AudioPlayer.stopAllEffect();
        this.unscheduleAllCallbacks();
        this.node.stopAllActions();
        this.isPassLock = false;
        this.isStar = false;
        this.level.string = `${level}`;
        localStorage.setItem("level",level);
        cc.loader.loadRes(`jiedian/level/level${level}`,cc.JsonAsset,(err,resp)=>{
            this.currLevelConfig = resp.json;
            this.initLevelScene();
            cc.tween(this.levelLayer).delay(1).to(1,{opacity:255}).delay(1).call(()=>{
                this.startDynamic()
                this.printG();
            }).start();
        })
    } 

    //开始启动带动态物理的
    startDynamic(){
        if(this.isStar)return;
        this.isStar = true;
        for (const key in this.balls) { 
            const ball = this.balls[key];
            ball.getComponent(Ball).opendDynamic();
        }
    }
 
    playSqueekEff(){
        let audioClip = this.squeek[MathUtil.getRandomInt(0,6)]
        AudioPlayer.playEffect(audioClip,false);
    }

    playShatterEff(){
        let audioClip = this.shatter[MathUtil.getRandomInt(0,6)]
        AudioPlayer.playEffect(audioClip,false);
    }

    /**
     * 初始化关卡场景
     */
    initLevelScene(){  
        //球 配置
        let points = this.currLevelConfig.points;
        //链接配置
        let sticks = this.currLevelConfig.sticks;
        
        this.balls = [];
        //创建球
        for (let index = 0; index < points.length; index++) {
            const config:Points = points[index];
            //创建球 
            let ball = null;
            if(this.ballPool.size() > 0){
                ball = this.ballPool.get();
            }else{
                ball = cc.instantiate(this.ballPrefab)
            }  
            ball.parent = this.levelLayer;
            let ballComp =ball.getComponent(Ball); 
            ballComp.init(config,index);
            ballComp.setTip(`${index}`);
            this.balls.push(ball); 
            //检查可以点击的次数
            if(config.clickable){
                this.limitClick +=1;
            }
        }   
        //创建线
        for (let index = 0; index < sticks.length; index++) {
            const config:Stick = sticks[index]; 
            //创建线
            let line:cc.Node = null;
            if(this.linePool.size() > 0){
                line = this.linePool.get();
            }else{
                line = cc.instantiate(this.linePrefab)
            }  
            line.parent = this.levelLayer;
            let lineComp = line.getComponent(Line); 
            lineComp.init(config,this.balls);
            this.lines.push(line); 
        }  
    }
     
    nextLevel(){ 
        cc.tween(this.levelLayer).to(1,{opacity:0}).delay(1).call(()=>{
            this.levelLayer.removeAllChildren();
            this.currLevelID += 1; 
            this.loadLevel(this.currLevelID);
        }).start();
    }

    resetLevel(){ 
         
        cc.tween(this.levelLayer).to(1,{opacity:0}).delay(1).call(()=>{
            this.levelLayer.removeAllChildren();
            this.loadLevel(this.currLevelID);
        }).start();
       
    }  
    recoveryPool(){
        let size = this.levelLayer.childrenCount;
        let children = this.levelLayer.children;
        for (const key in children) { 
            const element = children[key];
            if(element.name.indexOf("Ball") > -1){
                let rj = element.getComponent(cc.RopeJoint); 
                rj.connectedBody = null;
                rj.anchor = cc.v2(0,0) 
                this.ballPool.put(element);
            }
            if(element.name.indexOf("Line") > -1){  
                this.linePool.put(element);
            } 
        }  
        console.log("球池子"+this.ballPool.size())
        console.log("线池子"+this.ballPool.size())
    }
 
    checkClick(){  
        this.limitClick -= 1;
    }
    /**
     * 检查是否可以过关
     */
    checkPassLevel(){ 
        if(  this.isPassLock )return; 
        if(this.isPass()){
            this.isPassLock = true; 
            cc.tween(this.levelLayer).delay(2).to(1,{opacity:0}).call(()=>{ 
                this.nextLevel();
            }).start();
        }else{ 
            //console.log("检查通关2"+this.isPassLock,this.limitClick)
            if(this.isPassLock)return;
            if(this.limitClick <= 0 ){
                cc.tween(this.levelLayer).delay(2).call(()=>{
                    if(this.isPass() == false){
                        this.resetLevel();
                    }
                }).start() 
            } 
        } 
    } 

    isPass(){
        let isPassLevel = true;
        for (const key in this.balls) { 
            const element = this.balls[key]; 
            let spCom = element.getComponent("SpriteEx")
            if(spCom.index != BallType.BLACK){
                isPassLevel = false;
                break;
            }
        } 
        return isPassLevel;
    }

 
    printG(){
          

    }
     
}
